package com.org.any.autocar;

import java.io.File;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.autocar.reader.R;
import com.autocar.reader.bean.MsgBean;
import com.autocar.reader.bean.PersonBean;
import com.autocar.reader.bean.UserBean;
import com.autocar.reader.manager.LoadDataManager;
import com.autocar.reader.net.AsynThreadManager;
import com.autocar.reader.util.ConstantData;
import com.autocar.reader.util.ImageUtils;
import com.autocar.reader.util.NewDataToast;
import com.autocar.reader.util.PreferencesUtil;
import com.org.any.autocar.fragment.CameraController;
import com.org.any.autocar.fragment.CameraController.IDialogController;

public class UserInfoActivity extends BaseActivity {

	private LoadDataManager manager;
	private ImageView backView;
	private ScrollView chatCentreSv;
	private ImageView cPicIv;
	private EditText cZhEt;
	private EditText cEnEt;
	private EditText cCompanyEt;
	private EditText cSectionEt;
	private EditText cJobEt;
	private EditText cMobileEt;
	private EditText cPhoneEt;
	private EditText cEmailEt;
	private TextView cSaveTv;
	private PersonBean personBean;
	private PersonBean tempBean;
	private CameraController cameraCl;
	private UserBean ub;
	private String portraitPath;
	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// ����
	public static final int PHOTOZOOM = 2; // ���
	public static final int PHOTORESOULT = 3;// ���

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat_person_centered);
		initview();
		initproperty();
		loadPerson();
	}

	private void initproperty() {
		manager = LoadDataManager.getInstance();
		ub = PreferencesUtil.getUserbean(getApplicationContext());
	}

	private void loadPerson() {
		final String uid = ub.getUid();
		AsynThreadManager.doTask(new Runnable() {
			@Override
			public void run() {
				final PersonBean bean = manager.getPersonBean(uid, true);
				myHandler.post(new Runnable() {
					@Override
					public void run() {
						hideLoadPb();
						personBean = bean;
						if (bean != null) {
							if (bean.getStat() == 1) {
								initCenterValue(personBean);
							} else {
								showMsg(bean.getMsg());
							}
						}
					}
				});
			}
		});

	}

	private void initCenterValue(PersonBean bean) {
		this.cCompanyEt.setText(bean.getCompany());
		this.cEmailEt.setText(bean.getEmail());
		this.cEnEt.setText(bean.getEn_name());
		this.cJobEt.setText(bean.getJob());
		this.cZhEt.setText(bean.getZh_name());
		this.cSectionEt.setText(bean.getSection());
		this.cPhoneEt.setText(bean.getPhone());
		this.cMobileEt.setText(bean.getMobile());
		ImageUtils.fb.display(this.cPicIv, bean.getPhoto(),
				getDefautlBitmap(getApplicationContext()));
	}

	private void postPerson(final PersonBean bean, final String filePath) {
		showLoadPb();
		AsynThreadManager.doTask(new Runnable() {
			@Override
			public void run() {
				MsgBean mgb = manager.postPerson(ub.getUsername(), ub.getUid(),
						bean, filePath == null ? null : new File(filePath));
				Message msg = myHandler.obtainMessage(1, mgb);
				msg.sendToTarget();
			}
		});
	}

	private Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			hideLoadPb();
			switch (msg.what) {
			case 0:

				break;
			case 1:
				MsgBean bean = (MsgBean) msg.obj;
				if (bean == null) {
					showMsg("网络异常");
					return;
				}
				if (bean.getStat().equals("1")) { // �ɹ�
					String filePath = ConstantData.getPersonInfo();
					manager.getFileHandler().saveObj(tempBean, filePath);
				}
				showMsg(bean.getMsg());
				break;
			case -1:
				showMsg("网络异常");
				break;
			}
		};
	};

	private void initview() {
		this.backView = (ImageView) findViewById(R.id.chat_person_centered_top_iv_back);
		this.chatCentreSv = (ScrollView) findViewById(R.id.chat_person_centered_main_sl);
		initCview(chatCentreSv);

		this.backView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				gotoMain();
			}
		});
	}

	private void initCview(View v) {
		this.cCompanyEt = (EditText) v
				.findViewById(R.id.chat_person_centered_ev_company);
		this.cEmailEt = (EditText) v
				.findViewById(R.id.chat_person_centered_ev_email);
		this.cEnEt = (EditText) v
				.findViewById(R.id.chat_person_centered_ev_en_name);
		this.cJobEt = (EditText) v
				.findViewById(R.id.chat_person_centered_ev_job);
		this.cZhEt = (EditText) v
				.findViewById(R.id.chat_person_centered_ev_zh_name);
		this.cSectionEt = (EditText) v
				.findViewById(R.id.chat_person_centered_ev_department);
		this.cPicIv = (ImageView) v
				.findViewById(R.id.chat_person_centered_iv_pic);
		this.cPhoneEt = (EditText) v
				.findViewById(R.id.chat_person_centered_ev_tel_num);
		this.cMobileEt = (EditText) v
				.findViewById(R.id.chat_person_centered_ev_mobile_num);
		this.cSaveTv = (TextView) v
				.findViewById(R.id.chat_person_centered_tv_save);

		this.cSaveTv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				tempBean = new PersonBean();
				tempBean.setCompany(cCompanyEt.getText().toString());
				tempBean.setEmail(cEmailEt.getText().toString());
				tempBean.setEn_name(cEnEt.getText().toString());
				tempBean.setJob(cJobEt.getText().toString());
				tempBean.setMobile(cMobileEt.getText().toString());
				tempBean.setPhone(cPhoneEt.getText().toString());
				tempBean.setSection(cSectionEt.getText().toString());
				tempBean.setZh_name(cZhEt.getText().toString());
				postPerson(tempBean, portraitPath);
			}
		});
		cameraCl = new CameraController(this);
		cameraCl.setIDialogController(new IDialogController() {
			@Override
			public void doLocal() {
				gotoBrowse();
			}

			@Override
			public void doCamera() {
				gotoTake();
			}
		});
		this.cPicIv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				portraitPath = ConstantData.profileFile(System
						.currentTimeMillis() + ".jpg"); // ʱ���
				Log.e("mg", "portraitPath:  " + portraitPath);
				cameraCl.showPw(v);
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			gotoMain();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void gotoMain() {
		hideLoadPb();
		finish();
	}

	@Override
	public void finish() {
		super.finish();
		overridePendingTransition(R.anim.fade_in, R.anim.right_out_anim);
	}

	public void showMsg(String msg) {
		NewDataToast.makeText(getApplicationContext(), msg, false).show();
	}

	private void gotoTake() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(portraitPath)));
		startActivityForResult(intent, PHOTOHRAPH);
	}

	private void gotoBrowse() {
		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				"image/*");
		startActivityForResult(intent, PHOTOZOOM);
	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80); // ��������ü��Ŀ����
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHOTORESOULT);
	}

	public Bitmap getDefautlBitmap(Context context) {
		return BitmapFactory.decodeResource(context.getResources(),
				R.drawable.no_img_0);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		// ����
		if (requestCode == PHOTOHRAPH) {
			File picture = new File(portraitPath);
			startPhotoZoom(Uri.fromFile(picture));
		}

		if (data == null)
			return;

		// ��ȡ������ͼƬ
		if (requestCode == PHOTOZOOM) {
			startPhotoZoom(data.getData());
		}
		if (requestCode == PHOTORESOULT) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				Bitmap photo = extras.getParcelable("data");
				manager.getFileHandler().saveFile(photo, portraitPath);
				if (cPicIv != null) {
					cPicIv.setImageBitmap(photo);
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}
